class Course < ActiveRecord::Base
  include Comparable
  belongs_to :department
  has_many :sections
  
  #Associations with Major
  has_and_belongs_to_many :majors_requiring,
                          :join_table => 'required_courses',
                          :class_name => 'Major'
  has_and_belongs_to_many :majors_as_technical_elective,
                          :join_table => 'technical_electives',
                          :class_name => 'Major'
  has_and_belongs_to_many :majors_as_humanities_elective,
                          :join_table => 'humanities_electives',
                          :class_name => 'Major'
  has_and_belongs_to_many :majors_as_ss_elective,
                          :join_table => 'ss_electives',
                          :class_name => 'Major'
  
  #Student and Semester Associations                    
  has_many  :futures, :through => 'futures'
  has_many  :pasts,   :through => 'pasts'
  
  #Prerequirement self-association
  has_and_belongs_to_many :prerequisites, 
                          :join_table => 'prerequisites', 
                          :foreign_key => 'course_id',
                          :association_foreign_key => 'prerequisite_id',
                          :class_name => 'Course'
  has_and_belongs_to_many :postrequisites, 
                          :join_table => 'prerequisites',
                          :foreign_key => 'prerequisite_id',
                          :association_foreign_key => 'course_id',
                          :class_name => 'Course'
                          
  def self.with_number(number)
    Course.find(:first, :conditions => ["number = ?", number])
  end
  
  def self.uniq(array)
    ids = array.collect { |e| e.id }
    Course.find(ids.uniq)
  end
  
  def <=>(other_course)
    
    other_num = other_course.number.gsub(/\w+(\d{4})$/, '\1').to_i
    self_num = self.number.gsub(/\w+(\d{4})$/, '\1').to_i
    if (other_num == self_num) and (self.department != other_course.department)
      return -1*(self.department.id <=> other_course.department.id)
    else
      return self_num <=> other_num
    end
  end
  
  def elective_for_student?(student)
    return student.major.technical_electives.include?(self)
  end
  
  def registered_section
    self.sections.select { |e| e.registered? }.first
  end
  
  # def <(other)
  #   if (self <=> other) == -1
  #     return true
  #   else
  #     return false
  #   end 
  # end
  # 
  # def >(other)
  #   if (self <=> other) == 1
  #     return true
  #   else
  #     return false
  #   end
  # end
end
